package com.vaccination.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vaccination.entity.InoculationRecord;
import com.vaccination.entity.User;
import com.vaccination.service.UserService;
import com.vaccination.util.PageRequest;
import com.vaccination.util.PageResponse;
import com.vaccination.util.Result;
import net.sf.jsqlparser.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ModelAndView login(User request, ModelAndView mv, HttpServletRequest servletRequest) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", request.getUsername()).eq("password", request.getPassword()));
        if (user == null){
            mv.addObject("msg", "登陆失败，请检查账号或密码");
            mv.setViewName("login");
            return mv;
        }
        if (user.getStatus() == 2) {
            mv.addObject("msg", "账号被封禁，请联系管理员");
            mv.setViewName("login");
            return mv;
        }
        mv.addObject("username", request.getUsername());
        mv.setViewName("user");
        mv.addObject("isAdmin", user.getRole() == 2);
        servletRequest.getSession().setAttribute("loginUser", JSONObject.toJSONString(user));
        return mv;

    }

    @GetMapping("/logout")
    public ModelAndView logout(ModelAndView mv, HttpServletRequest request) {
        mv.setViewName("login");
        mv.addObject("msg", "退出成功");
        request.getSession().removeAttribute("loginUser");
        return mv;
    }

    @PostMapping("/reg")
    public ModelAndView reg(User request, ModelAndView mv) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", request.getUsername()));
        if (user != null){
            mv.addObject("msg", "注册失败，用户名已存在");
            mv.setViewName("reg");
            return mv;
        }
        request.setName(request.getUsername());
        mv.addObject("username", request.getUsername());
        mv.addObject("msg", "注册成功，请登陆");
        userService.save(request);
        mv.setViewName("login");
        return mv;

    }

    @GetMapping("/userInfo")
    public ModelAndView userInfo(ModelAndView mv, HttpServletRequest request){
        mv.setViewName("userInfo");
        String user = (String) request.getSession().getAttribute("loginUser");
        User byId = userService.getById(JSONObject.parseObject(user, User.class).getId());
        mv.addObject("user",byId);
        request.getSession().setAttribute("loginUser", JSONObject.toJSONString(byId));
        return mv;
    }

    @PostMapping("/saveUserInfo")
    public Result saveUserInfo(User request, HttpServletRequest servletRequest) {
        User user = JSONObject.parseObject((String) servletRequest.getSession().getAttribute("loginUser"), User.class);
        request.setId(user.getId());
        userService.updateById(request);
        servletRequest.getSession().setAttribute("loginUser", JSONObject.toJSONString(request));
        return Result.success("修改成功");
    }

    @PostMapping("/listUser")
    public PageResponse listUser(PageRequest page, HttpServletRequest request) {
        String loginUser = (String) request.getSession().getAttribute("loginUser");
        User user = JSONObject.parseObject(loginUser, User.class);
        if (user == null) {
            return new PageResponse("500","请登陆",0L,  new ArrayList<>());
        }
        if (user.getRole() == 1) {
            return new PageResponse("500","没有权限",0L,  new ArrayList<>());
        }
        IPage<User> iPage = userService.listPage(new Page<>(page.getPage(), page.getLimit()));
        return new PageResponse("0", "请求成功", iPage.getTotal(), iPage.getRecords());
    }

    @GetMapping("/getUserById/{id}")
    public ModelAndView getUserById(@PathVariable("id") Long userId, ModelAndView mv) {
        User byId = userService.getById(userId);
        mv.addObject("user", byId);
        mv.setViewName("editUser");
        return mv;
    }

    @GetMapping("/enableUser")
    public Result enableUser(Long id) {
        User byId = userService.getById(id);
        byId.setStatus(1);
        userService.updateById(byId);
        return Result.success("启用成功");
    }

    @GetMapping("/disableUser")
    public Result disableUser(Long id) {
        User byId = userService.getById(id);
        byId.setStatus(2);
        userService.updateById(byId);
        return Result.success("禁用成功");
    }

    @GetMapping("delUser")
    public Result delUser(Long id) {
        userService.removeAll(id);
        return Result.success("删除成功");
    }

    @PostMapping("/updateUser")
    public Result updateUser(User user) {
        User username = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (username != null && !username.getId().equals(user.getId())) {
            return Result.error("用户名已存在");
        }
        userService.updateById(user);
        return Result.success("修改成功");
    }
}
